package com.example.recycleview;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class MyDAO {
    private SQLiteDatabase database;
    private Cursor cursor,cursor2;
    private List name=new ArrayList();
    private int average;

    public MyDAO(Context context) {
        MyOpenHelper myOpenHelper = new MyOpenHelper(context,
                "Mysqlite5",null,1);
        database = myOpenHelper.getWritableDatabase();

    }

    public void MyInsert(String name,int age){
        ContentValues contentValues = new ContentValues();
        contentValues.put("name",name);
        contentValues.put("age",age);
        database.insert("person",null,contentValues);
    }

    public void MyUpdate(String name,int age){
        ContentValues contentValues2 = new ContentValues();
        contentValues2.put("age",age);
        database.update("person",contentValues2,"name=?",new String[]{name});
    }
    public void  MyDelete(String name){
        database.delete("person","name=?",new String[]{name});
    }

    @SuppressLint("Range")
    public List MyQuery(String age_Str){
        int i=0;
        cursor= database.rawQuery("select * from person where age>?",new String[]{age_Str});//查询age>age_Str的数据
        while (cursor.moveToNext()){
            name.add(cursor.getString(cursor.getColumnIndex("name")));

        }
        cursor.close();
        return name;
    }

    @SuppressLint("Range")
    public int average() {
        int sum = 0;
        int count = 0;
        cursor2 = database.rawQuery("select * from person", null);
        while (cursor2.moveToNext()) {
            count++;
            sum += cursor2.getInt(cursor2.getColumnIndex("age"));
            /*Log.d("sqlite",name);*/
        }
        cursor.close();
        average =Math.round(sum / count) ;
        return average;

    }
}
